import 'package:chatgreat/helper/ability.dart';
import 'package:chatgreat/helper/cache.dart';
import 'package:chatgreat/helper/constant.dart';
import 'package:chatgreat/helper/event.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/bloc/room_bloc.dart';
import 'package:chatgreat/page/chat/room_create.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/enhanced_button.dart';
import 'package:chatgreat/page/component/enhanced_error.dart';
import 'package:chatgreat/page/component/enhanced_popup_menu.dart';
import 'package:chatgreat/page/component/global_alert.dart';
import 'package:chatgreat/page/component/loading.dart';
import 'package:chatgreat/page/component/room_card.dart';
import 'package:chatgreat/page/component/sliver_component.dart';
import 'package:chatgreat/page/component/weak_text_button.dart';
import 'package:chatgreat/page/component/dialog.dart';
import 'package:chatgreat/page/chat/component/room_item.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/api/room_gallery.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:go_router/go_router.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../helper/color.dart';

//助理首页
class RoomsPage extends StatefulWidget {
  final SettingRepository setting;
  const RoomsPage({Key? key, required this.setting}) : super(key: key);

  @override
  State<RoomsPage> createState() => _RoomsPageState();
}

class _RoomsPageState extends State<RoomsPage> {
  List<RoomGallery> suggests = [];
  int page = 1;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    context.read<RoomBloc>().add(RoomsLoadEvent());

    GlobalEvent().on("refresh_3", (data) {
      if (mounted) {
        _refreshController.requestRefresh();
      }
    });
    super.initState();
  }

  List<RoomGallery> selectedSuggestions = [];

  @override
  Widget build(BuildContext context) {
    var customColors = Theme.of(context).extension<CustomColors>()!;
    return BackgroundContainer(
      setting: widget.setting,
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/bg1.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          body: BlocConsumer<RoomBloc, RoomState>(
            listener: (context, state) {
              if (state is RoomsLoaded) {
                if (state.rooms.isNotEmpty) {
                  selectedSuggestions.clear();
                  setState(() {});
                  GlobalEvent().emit('showBottomNavigatorBar');
                }
                if (page == 1) {
                  suggests.clear();
                }
                suggests.addAll(state.suggests);
                _refreshController.refreshCompleted();
                _refreshController.loadComplete();
              }

              if (state is RoomCreateError) {
                showErrorMessageEnhanced(context, state.error);
              }

              if (state is RoomOperationResult) {
                if (state.success) {
                  if (state.redirect != null) {
                    context.push(state.redirect!, extra: {'name': state.name, 'avater': state.avater}).then((value) {
                      // 刷新
                      // context.read<RoomBloc>().add(RoomsLoadEvent());
                    });
                  }
                } else {
                  showErrorMessageEnhanced(context, state.error ?? '操作失败');
                }
              }
            },
            buildWhen: (previous, current) =>
                current is RoomsLoading || current is RoomsLoaded,
            builder: (context, state) {
              if (state is RoomsLoaded) {
                if (state.error != null) {
                  return EnhancedErrorWidget(
                      error: state.error,
                      onTap: () {
                        context.read<RoomBloc>().add(RoomsLoadEvent());
                      });
                }

                return SliverCreateComponent(
                  title: const Text(
                    "助理",
                    style: TextStyle(
                      fontSize: CustomSize.appBarTitleSize,
                      color: Colors.white,
                    ),
                  ),
                  backgroundImage: Image.asset(
                    customColors.appBarBackgroundImageForRoom!,
                    fit: BoxFit.cover,
                  ),
                  child: SafeArea(
                    child: SmartRefresher(
                      enablePullDown: true,
                      enablePullUp: true,
                      header: WaterDropHeader(
                          waterDropColor: stringToColor('FF4F6CEF')),
                      footer: CustomFooter(
                          builder: (BuildContext context, LoadStatus? mode) {
                        Widget body;
                        if (mode == LoadStatus.idle) {
                          return const SizedBox();
                        } else if (mode == LoadStatus.loading) {
                          body = const CupertinoActivityIndicator();
                        } else if (mode == LoadStatus.failed) {
                          body = const Text("加载失败！点击重试！");
                        } else if (mode == LoadStatus.canLoading) {
                          body = const Text("松手，加载更多！");
                        } else {
                          body = const Text("没有更多数据了！");
                        }
                        return SizedBox(
                          height: 55.0,
                          child: Center(child: body),
                        );
                      }),
                      onRefresh: () async {
                        page = 1;
                        context.read<RoomBloc>().add(
                            RoomsLoadEvent(forceRefresh: true, page: page));
                      },
                      onLoading: () {
                        page += 1;
                        context.read<RoomBloc>().add(
                            RoomsLoadEvent(forceRefresh: true, page: page));
                      },
                      controller: _refreshController,
                      child: buildBody(customColors, state, context),
                    ),
                  ),
                );
              }

              return const Center(
                child: LoadingIndicator(),
              );
            },
          ),
          // bottomNavigationBar: selectedSuggestions.isNotEmpty
          //     ? SafeArea(
          //         child: Container(
          //           height: 70,
          //           width: double.infinity,
          //           padding: const EdgeInsets.symmetric(
          //             horizontal: 20,
          //             vertical: 10,
          //           ),
          //           child: Row(
          //             children: [
          //               WeakTextButton(
          //                 title: '取消',
          //                 onPressed: () {
          //                   selectedSuggestions.clear();
          //                   setState(() {});
          //                   GlobalEvent().emit('showBottomNavigatorBar');
          //                 },
          //               ),
          //               const SizedBox(width: 20),
          //               Expanded(
          //                 child: EnhancedButton(
          //                     title: AppLocale.ok.getString(context),
          //                     onPressed: () {
          //                       context.read<RoomBloc>().add(
          //                           GalleryRoomCopyEvent(selectedSuggestions
          //                               .map((e) => e.id)
          //                               .toList()));
          //                       showSuccessMessage(AppLocale.operateSuccess
          //                           .getString(context));
          //                     }),
          //               )
          //             ],
          //           ),
          //         ),
          //       )
          //     : null,
        ),
      ),
    );
  }

  Widget buildBody(
      CustomColors customColors, RoomsLoaded state, BuildContext context) {
    // 暂时用这里
    if (suggests.isNotEmpty && state.rooms.isEmpty) {
      return GridView.count(
        shrinkWrap: true,
        addAutomaticKeepAlives: false,
        addRepaintBoundaries: false,
        crossAxisCount: 2,
        childAspectRatio: 0.73,
        padding: const EdgeInsets.only(left: 15, right: 15),
        mainAxisSpacing: 15,
        crossAxisSpacing: 15,
        children: [
          ...suggests
              .map((item) => RoomCard(
                    item: item,
                    onItemSelected: onItemSelected,
                    selected: selectedSuggestions.contains(item),
                    selectedCheck: () {
                      if (selectedSuggestions.isNotEmpty) {
                        return;
                      }
                      GlobalEvent().emit('showBottomNavigatorBar');
                    },
                  ))
              .toList(),
        ],
      );
    }

    return SafeArea(
      top: false,
      child: ListView.builder(
        padding: const EdgeInsets.all(5),
        itemCount: state.rooms.length,
        itemBuilder: (context, index) {
          final room = state.rooms[index];

          return RoomItem(room: room);
        },
      ),
    );
  }

  // 选中单个助理
  void onItemSelected(RoomGallery item) {
    context.read<RoomBloc>().add(
          RoomCreateEvent(item.id, item.name, avatarUrl: item.avatarUrl),
        );
  }
}
